import { Component, OnInit ,ViewChild, HostListener} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ClueDataService } from '../../../../@core/service/clue-service/clue-data.service';
import { HandleTableService } from '../../../../@core/service/clue-service/handle-table.service';
import * as moment from 'moment' 
import { TableComponent } from './table/table.component';
import { AreaInfoVo } from './../../../../@core/service/person-select-service/model/areaInfoVo';
import { CaseService} from '../../../../@core/service/handle-service/api/case.service'
@Component({
  selector: 'app-handle',
  templateUrl: './handle.component.html',
  styleUrls: ['./handle.component.scss']
})
export class HandleComponent implements OnInit {
  // 案件来源数据
  public handleOriginList:any[];
  // 办理事项数据
  public handleStatusList:any[];
  // 案件类型数据
  public handleTypeList:any[];
  //登记机关
  public regAuthList:any;
  //地区list
  public areaList:any[];
  // 模块类型  区分是 案件审批还是案件办理
  public modelType:string;
  // 新增按钮权限
  public addPermiss: boolean;
  // 按钮标识
  public btnPerssion: any;


  @ViewChild('table') table:TableComponent;

  public areaData:any={
    province:{},
    city :{},
    county:{},
    showArea:null,
    lastKey:null
  } 
  //定义参数 双向绑定数据
  public handle={ 
    handleOriginValue: null,   // 案件来源
    handleType: null,          // 案件类型
    partyName: null,           // 当事人
    dataStart: null,           // 起始时间
    dataEnd: null,             // 结束时间
    handleArea: {
      "province":null,"city":null,"county":null
    },                         // 案件地区
    handleStatus: null         // 办理状态
  }

  //选择条目
  selectedLimit: any;

  //初始化构造函数  
  constructor(
    private clueData: ClueDataService,
    private handleTable: HandleTableService,
    private caseService:CaseService,
    private active: ActivatedRoute) { 
    this.handleOriginList = clueData.source;
    this.handleStatusList =  [{
      "name": "全部状态",
      "value": "-1"
    },  
    {
      "name": "待办理",
      "value": "01"
    },
    {
      "name": "已完成",
      "value": "04"
    }
    ]
    this.handleTypeList = clueData.handleType;
    this.regAuthList = clueData;
    this.areaList = clueData.area;
   
  }

  ngOnInit() {
    let options ={
      type:  null,
      sourceType: null,
      caseType: null,
      currentStatus: null,
      currentLink: null,
      partyName: null,
      enrollmentStartDate: null,
      enrollmentEndDate: null,
      area: null
    }
    this.handleTable.setOption(options);
    this.active.data.subscribe(data => {
      this.modelType = data['type'];
      this.addPermiss = data['addPermissions'];
      if (this.modelType == 'handle') {
        this.btnPerssion = {
          'insert': 'handle_case_insert',          // 案件新增  
        }
      } else {
        this.btnPerssion = {
          'insert': 'approval_case_insert',        // 案件新增          
          'export': 'approval_case_export'
        }
      }
    });
    // console.log(this.title);
    if(document.getElementsByClassName('box-body').length>0){
        let h = document.documentElement.clientHeight || document.body.clientHeight;
        let Body:any = document.getElementsByClassName('box-body')[0]
        Body.style.height =h-230+`px`;
    } 
  }
 
  

  //统一change方法调用
  onStartChange(date:any):void{
    if(date){
      let d = new Date(date);
      let datetime = moment(d).format('YYYY-MM-DD')
      this.handle.dataStart = datetime;
    }else{
      this.handle.dataStart = ''
    }
  }
  onCloseChange(date:any):void{
    if(date){
      let d = new Date(date);
      let datetime = moment(d).format('YYYY-MM-DD')
      this.handle.dataEnd = datetime;
    }else{
      this.handle.dataEnd = ''
    }
  }

  // select 双向数据绑定的value 获取 name
  selectOptionName(optionValue, data) {
    let result = '';
    data.forEach(ele => {
      if (ele['value'] == optionValue) {
        result = ele['name'];
      }
    });
    return result;
  }  

  // 调用查询方法
  search(){
    let handleType = this.selectOptionName(this.handle.handleType, this.handleTypeList);
    let handleStatus = this.selectOptionName(this.handle.handleStatus, this.handleStatusList);
    let areaInfo = null;
    if (this.areaData['province']['option']&&this.areaData['province']['option']!=null) {
      this.handle.handleArea.province = this.areaData['province']['option']['key'];
      this.handle.handleArea.city = this.areaData['city']['option']['key'];
      this.handle.handleArea.county = this.areaData['county']['option']['key'];
      areaInfo = typeof(this.handle.handleArea) == 'string' ? this.handle.handleArea 
                    : JSON.stringify(this.handle.handleArea);
    }
   
    let options ={
      type: this.modelType || null,
      sourceType: this.handle.handleOriginValue||null,   // 案件来源
      caseType: handleType||null,                        // 案件类型
      caseStatus: handleStatus||null,                 // 办理状态
      partyName: this.handle.partyName||null,            // 当事人
      enrollmentStartDate: this.handle.dataStart||null,  // 登记开始时间
      enrollmentEndDate: this.handle.dataEnd||null,      // 登记结束时间
      area: areaInfo  || null                            // 地区
    }
    this.handleTable.setOption(options);
    this.table.pageInator.onSetPageValue(1)
    this.table.goToPage({type: this.modelType, num:1,limit:this.table.selectedLimit}) 
  }

  // 调用reset方法
  reset(){
    this.handle.dataStart = ''
    this.handle.dataEnd = ''
    this.areaData={
      province:{},
      city :{},
      county:{},
      showArea:null,
      lastKey:null
    } 
    this.handle.dataEnd = null;
    this.handle.dataStart = null;
    this.handle.handleArea = {
      "province":null,"city":null,"county":null
    };
    this.handle.handleOriginValue = null;
    this.handle.handleStatus = null;
    this.handle.handleType = null;
    this.handle.partyName = null;
    this.search()
  }

  // 导出
  export(){
    let handleType = this.selectOptionName(this.handle.handleType, this.handleTypeList);
    let handleStatus = this.selectOptionName(this.handle.handleStatus, this.handleStatusList);
    let areaInfo = null;
    if (this.areaData['province']['option']&&this.areaData['province']['option']!=null) {
      this.handle.handleArea.province = this.areaData['province']['option']['key'];
      this.handle.handleArea.city = this.areaData['city']['option']['key'];
      this.handle.handleArea.county = this.areaData['county']['option']['key'];
      areaInfo = typeof(this.handle.handleArea) == 'string' ? this.handle.handleArea 
                    : JSON.stringify(this.handle.handleArea);
    }

    this.caseService.caseExportGet(
      this.handle.handleOriginValue||null,   // 案件来源
      handleType||null,                      // 案件类型
      null,                                  // 办理状态
      null,
      this.handle.partyName||null,           // 当事人
      sessionStorage.getItem('userId'),      // 当前登陆人
      this.handle.dataStart||null,           // 登记开始时间
      this.handle.dataEnd||null,             // 登记结束时间
      areaInfo,                              // 地区
      handleStatus,                          // 办理状态
      'response'
      ).subscribe((data:any)=>{
        let blob = data.body;
        let filename = data.headers.get('content-disposition').split('filename=')[1];
        this.imatateDownloadByA(window.URL.createObjectURL(blob), filename);
      })
  }

  // 通过a标签模拟下载
  imatateDownloadByA (href, filename) {
    const a = document.createElement('a')
    a.download = filename
    a.style.display = 'none'
    a.href = href
    document.body.appendChild(a)
    a.click()
    a.remove()
    window.URL.revokeObjectURL(href)
   }

  //设置areaSelect
  onSelection(event):void{
    if(event){
      if(event.index == 0){
        this.areaData['province']['option'] = event.option;
        this.areaData['city']['option']  = null;
        this.areaData['county']['option']  = null;
        this.areaData.showArea = `${this.areaData['province']['option']['label']}`;
      }else if(event.index == 1){
        this.areaData['city']['option']  = event.option;
        this.areaData['county']['option']  = null;
        this.areaData.showArea = `${this.areaData['province']['option']['label']}-${this.areaData['city']['option']['label']}`;
      }else if(event.index == 2){
        this.areaData['county']['option']  = event.option;
        this.areaData.showArea = `${this.areaData['province']['option']['label']}-${this.areaData['city']['option']['label']}-${this.areaData['county']['option']['label']}`;
      }
    }else{
      this.areaData['province']['option']=null
      this.areaData['city']['option']  = null;
      this.areaData['county']['option']  = null;
      this.areaData.showArea=null;
      this.areaData.lastKey = null;
    }
  }
  //修改select传递参数
  onSelectionFn(event){
    this.areaData.lastKey =  event.pop()['key']
  }
  //slection清除方法
  selectionClear(){
    this.areaData['province']['option']=null
    this.areaData['city']['option']  = null;
    this.areaData['county']['option']  = null;
    this.areaData.showArea=null;
  }

  //日期框打开关闭事件
  onStartClose(event){
    if(!event){
      this.handle.dataStart = ''
    }
    
  }
  onEndClose(event){
    if(!event){
      this.handle.dataEnd = ''
    }
  }

}
